/*****************************************************************************
 *
 *  socket_tcp_fork_server.c
 *
 *  Created on: 2012-3-11
 *      Author: Michael
 *       Email: zhongchao.ustc@gmail.com
 *
 *  Copyright (c) Michael Chao Zhong
 *
 *****************************************************************************/

#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <stdlib.h> 

int main(int argc, char *argv[])
{
	// Get options
	if (argc < 3)
	{
		fprintf(stderr, "Usage: %s <hostname> <port>\n", argv[0]);
		exit(1);
	}
	struct hostent *server_host = gethostbyname(argv[1]);
	int server_port = atoi(argv[2]);

	// Get socket
	int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
	
	// Connect
	struct sockaddr_in server_addr;
	bzero((char *) &server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	bcopy((char *) server_host->h_addr, (char *) &server_addr.sin_addr.s_addr,
			server_host->h_length);
	server_addr.sin_port = htons(server_port);
	connect(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr));
	
	// Input
	printf("Please enter the message: ");
	char buffer[1024];
	bzero(buffer, sizeof(buffer));
	fgets(buffer, sizeof(buffer) - 1, stdin);

	// Write
	write(socket_fd, buffer, strlen(buffer));

	// Read
	bzero(buffer, sizeof(buffer));
	read(socket_fd, buffer, sizeof(buffer) - 1);
	printf("%s\n", buffer);

	// Close
	close(socket_fd);

	return 0;
}
